/* Plugin code starts here */
(function($) {
	$.fn.editAtPlace = function(callback) {
		return this.each(function() {
			var clickFn = function(){
				var el = $(this);
				var pHtml = el.html();
				var nHtml = "<input id='editInPlaceText' type='text' value='" + pHtml + "'></input>";
				$(this).html(nHtml);

				var onComplete = function(newText) {
					if(callback) {
						el.html(newText);
						el.bind('click', clickFn);
						callback(newText, pHtml);
					}
				};
				// On Focus of text box, unbind the click event for el
				$('#editInPlaceText').focusin(function() {
					el.unbind('click', clickFn);
				});
				// For ENTER key, bind click event to el again and call the callback function
				$('#editInPlaceText').keyup(function(e) {
					if(e.keyCode == 13) {
						var value = e.target.value;
						if(! value.match("^\\s+$") && value != "")
							onComplete(value);
						else
							onComplete(pHtml);
					}
				});
				// On Foucus out of text box, bind click event to el again and call the callback function
				$('#editInPlaceText').focusout(function(e) {
					var value = e.target.value;
					if(! value.match("^\\s+$") && value != "") {
						onComplete(value);}
					else {
						onComplete(pHtml);}
				});
				// Give focus to new text box
				$('#editInPlaceText').focus();
			}
			$(this).bind("click", clickFn);
		});
	}
})(jQuery); /* Plugin code ends */